# -*- coding = utf-8 -*-
from flask import Flask,jsonify,render_template,request,escape
from panduan import panduan,xieru
from gaode import geocode,weatherinfo,staticmap
import requests,json
import pandas as pd
from PIL import Image
from io import BytesIO
import direction_of_bicycling
import direction_of_walking
import direction_of_driving
import direction_of_bus
import direction_of_ddcx
import ddgx
import os
#调用各种需要用到的库，文件等
xu_key = "9bce68c83a431dbc61cacc81a1de087b"
app = Flask(__name__)
#将API调用密匙单独写出来，本程序为了增加用户的参与感，让用户动手输入密匙（就像真的购买了软件那样）
#如果不想这么干，把程序中的所以key都换成xu_key即可

os.system('read_first.py')

def log_request(req:"flask_request",res:str):
	with open("view.log","a") as log:
		print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')
#打开日志，对日志进行写入用户名，登录信息等内容

# 起始界面
@app.route("/",methods = ["GET"])
def base() ->"html":
	return render_template("base.html")

# 登录界面
@app.route("/login",methods = ["GET"])
def login():
	return render_template("login.html")

# 注册界面
@app.route("/registered1",methods = ["GET"])
def registered_zhuce() ->"html":
	return render_template("registered1.html")

# 注册成功界面
@app.route("/registeredok1",methods = ["POST"])
def registered_ok() ->"html":
	zhuce_zhanghao = request.form["zhuce-zhanghao"]
	zhuce_mima = request.form["zhuce-mima"]
	xieru(zhuce_zhanghao,zhuce_mima)
	return render_template("registeredok1.html")
#从regist网页中获取用户名，密码信息

# 功能选择界面
@app.route("/start",methods = ["POST"])
def start():
	zhanghao = request.form["zhanghao"]
	mima = request.form["mima"]
	zhanghao=int(zhanghao)
	mima = int(mima)
	a = panduan(zhanghao,mima)
	log_request(request,a)
	if a == "true":#登录成功显示成功界面
		return render_template("start.html")
	else:#登录失败显示失败界面
		return render_template("loginfail.html",loginfail = "登录失败")

# 天气查询界面选择
@app.route("/tianqi",methods = ["POST"])
def yangshi():
	return render_template("tianqi.html")

# 天气查询成功界面，调用天气查询API，返回相应的信息
@app.route("/search",methods = ["POST"])
def hello_login():
	maincity = request.form["city"]
	tianqi = weatherinfo(maincity)
	province1 = tianqi["lives"][0]['province']
	city1 = tianqi["lives"][0]['city']
	adcode1 = tianqi["lives"][0]['adcode']
	weather1 = tianqi["lives"][0]['weather']
	temperature1 = tianqi["lives"][0]['temperature']
	winddirection1 = tianqi["lives"][0]['winddirection']
	windpower1 = tianqi["lives"][0]['windpower']
	humidity1 = tianqi["lives"][0]['humidity']
	reporttime1 = tianqi["lives"][0]['reporttime']
	return render_template(
		"tianqijieguo.html",
		the_geocode = tianqi,
		province = province1,
		city = city1,
		adcode = adcode1,
		weather = weather1,
		temperature = temperature1,
		winddirection = winddirection1,
		windpower = windpower1,
		humidity = humidity1,
		reporttime = reporttime1
		)

# 骑行路径查询界面选择
@app.route("/bicycle",methods = ["GET"])
def mapstart():
	return render_template("bicyclestart.html")

# 骑行路径生成界面，从骑行查询界面获取起点和终点，带入direction_bicycling函数进行运算，获取查询的信息
@app.route("/bicyclejieguo",methods = ["POST"])
def do_search_0() -> 'html':
    key = request.form['key']
    start_address = request.form['start_address']
    end_address = request.form['end_address']
    title = '查询结果'
    df = direction_of_bicycling.direction_bicycling(key,start_address, end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration']]
    results.columns = ['指引', '路程', '时间']
    total_bicycle = direction_of_bicycling.total_bicycle(df)
    total_bicycle_time = direction_of_bicycling.total_bicycle_time(df)
    route = results['指引'].tolist()
    log_request(request, route)#将查询到的数据反馈到网页端进行显示，下面同理
    return render_template('bicyclejieguo.html',
                           the_title=title,
                           the_start_address=start_address,
                           the_end_address=end_address,
                           the_results=results,
                           the_html_table=results.to_html(index=False),
                           the_total_bicycle=total_bicycle,
                           the_total_bicycle_time=total_bicycle_time,)


# 步行路径查询界面
@app.route("/walk",methods = ["GET"])
def mapstart1():
	return render_template("walkstart.html")

# 步行路径生成界面
@app.route("/walkjieguo",methods = ["POST"])
def do_search_1() -> 'html':
    key = request.form['key']
    start_address = request.form['start_address']
    end_address = request.form['end_address']
    title = '查询结果'
    df = direction_of_walking.direction_walking(key,start_address,end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration']]
    results.columns = ['指引', '路程', '时间']
    total_walk = direction_of_walking.total_walk(df)
    total_walk_time = direction_of_walking.total_walk_time(df)
    route = results['指引'].tolist()
    log_request(request, route)
    return render_template('walkjieguo.html',
						   the_title=title,
						   the_start_address=start_address,
						   the_end_address=end_address,
						   the_results=results,
						   the_html_table=results.to_html(index=False),
						   the_total_walk=total_walk,
						   the_total_walk_time=total_walk_time,)

# 驾车路径查询界面
@app.route("/drive",methods = ["GET"])
def mapstart2():
	return render_template("drivestart.html")

# 驾车路径生成界面
@app.route("/drivejieguo",methods = ["POST"])
def do_search_2() -> 'html':
    key = request.form['key']
    start_address = request.form['start_address']
    end_address = request.form['end_address']
    title = '查询结果'
    df = direction_of_driving.direction_driving(key,start_address,end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration']]
    results.columns = ['指引', '路程', '时间']
    total_drive = direction_of_driving.total_drive(df)
    total_drive_time = direction_of_driving.total_drive_time(df)
    route = results['指引'].tolist()
    log_request(request, route)
    return render_template('drivejieguo.html',
						   the_title=title,
						   the_start_address=start_address,
						   the_end_address=end_address,
						   the_results=results,
						   the_html_table=results.to_html(index=False),
						   the_total_drive=total_drive,
						   the_total_drive_time=total_drive_time,)

# 公共交通路径查询界面
@app.route("/bus",methods = ["GET"])
def mapstart3():
	return render_template("busstart.html")

# 公共交通路径生成界面
@app.route("/busjieguo",methods = ["POST"])
def do_search_3() -> 'html':
    key = request.form['key']
    start_address = request.form['start_address']
    end_address = request.form['end_address']
    title = '查询结果'
    df = direction_of_bus.direction_bus(key,start_address,end_address)
    results = df.loc[:, ['name','type', 'id','distance','duration']]
    results.columns = ['名称','类型', '编号','路程','时间']
    total_bus = direction_of_bus.total_bus(df)
    total_bus_time = direction_of_bus.total_bus_time(df)
    route = results['名称'].tolist()
    log_request(request, route)
    return render_template('drivejieguo.html',
						   the_title=title,
						   the_start_address=start_address,
						   the_end_address=end_address,
						   the_results=results,
						   the_html_table=results.to_html(index=False),
						   the_total_bus=total_bus,
						   the_total_bus_time=total_bus_time,)


# 多点路径方案查询查询界面
@app.route("/ljcx",methods = ["GET"])
def mapstart4():
	return render_template("ldcx.html")

# 多点路径方案查询查询生成界面
@app.route("/ljcxjieguo",methods = ["POST"])
def do_search_4() -> 'html':
	key = request.form['key']
	n_sum = request.form['n_num']

	start_address1 = request.form['start_address1']#从网页中获取到所有输入的地址字符串
	start_address2 = request.form['start_address2']
	start_address3 = request.form['start_address3']
	start_address4 = request.form['start_address4']
	start_address5 = request.form['start_address5']
	start_address6 = request.form['start_address6']
	start_address7 = request.form['start_address7']

	#跟据输入点的数量进行获取经纬度坐标和对地址信息进行合并
	if n_sum == '4':
		df = direction_of_ddcx.direction_ddcx1(key,start_address1,start_address2,start_address3,start_address4)
		cf = direction_of_ddcx.direction_ddbc1(start_address1,start_address2,start_address3,start_address4)

	elif n_sum == '5':
		df = direction_of_ddcx.direction_ddcx2(key,start_address1, start_address2,start_address3,start_address4,start_address5)
		cf = direction_of_ddcx.direction_ddbc2(start_address1, start_address2, start_address3, start_address4,start_address5)

	elif n_sum == '6':
		df = direction_of_ddcx.direction_ddcx3(key,start_address1, start_address2,start_address3,start_address4,start_address5,start_address6)
		cf = direction_of_ddcx.direction_ddbc3(start_address1, start_address2,start_address3,start_address4,start_address5,start_address6)

	else:
		df = direction_of_ddcx.direction_ddcx4(key,start_address1, start_address2,start_address3,start_address4,start_address5,start_address6,start_address7)
		cf = direction_of_ddcx.direction_ddbc3(start_address1, start_address2,start_address3,start_address4,start_address5,start_address6,start_address7)

	#调用ddgx中gh的函数进行多点运算
	results = ddgx.gh(n_sum,df,cf)
	#将运算后的信息显示到网页
	return render_template('ljcxjieguo.html',
						   the_html_table=results,)

# 日志界面,从日志数据库中获取和写入信息
@app.route("/viewlog")
def view_log():
	with open("view.log","r") as log:
		contents = []
		for line in log:
			contents.append([])
			for item in line.split('|'):
				contents[-1].append(escape(item))
	titles = ["Form data","remote_addr","User_agent","Results"]
	return render_template("viewlog.html",
		the_data = contents,
		the_title = titles
	)


if __name__ == '__main__':
	app.run(debug=True)